<?php

namespace App\Utils;

use Validator;
use DB;
use App\Cache\BaseCache;
use AliyunSms;
use Log;

include_once __DIR__ . '/../Library/aliyun-dysms-php-sdk/AliyunSms.php';

class CommonUtils {

    protected $uuidKey = 'welcomeToBeijing';
    protected $request = null;

    public function __construct($request = null) {
        $this->request = $request;
    }

    /*     *
     * @description : 发送短信
     * @param: $message 短信内容
     * @return: 
     */

    public function sendShortMessage($message) {
        //调用示例：
        set_time_limit(0);
        header('Content-Type: text/plain; charset=utf-8');
        try {
            $response = AliyunSms::sendSms(
                            "彩云之端文化传媒", // 短信签名
                            "SMS_114385633", // 短信模板编号
                            $message['phone'], // 短信接收者
                            Array(// 短信模板中字段的值
                        "code" => $message['code'],
                        "product" => ""
                            ), ""   // 流水号,选填
            );
        } catch (Exception $exc) {
            return FALSE;
        }
        if ($response) {
            if ($response->Message == "OK") {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

//stdClass Object
//(
//    [Message] => OK
//    [RequestId] => 00CD7FE7-A3ED-4F03-8EAF-13C283BADCFF
//    [BizId] => 675309311243795633^0
//    [Code] => OK
//)
//        stdClass Object
//        (
//            [Message] => 模板不合法(不存在或被拉黑)
//            [RequestId] => 35A2C653-6633-4BF0-B721-2E8FC75935A6
//            [Code] => isv.SMS_TEMPLATE_ILLEGAL
//        )
//        exit();
//        sleep(2);
//        $response = AliyunSms::queryDetails(
//                        "12345678901", // phoneNumbers 电话号码
//                        "20170718", // sendDate 发送时间
//                        10, // pageSize 分页大小
//                        1 // currentPage 当前页码
//                        // "abcd" // bizId 短信发送流水号，选填
//        );
//        echo "查询短信发送情况(queryDetails)接口返回的结果:\n";
//        print_r($response);
//    }

    /*     *
     * @description : 校验参数是否是用户名 0 都不是  1 email 2 phone
     * @param: $name， 用户名 email or phone
     * @return: 0 都不是  1 email 2 phone
     */

    public function isEmailorPhone($name) {
        //邮箱的验证
        $validator = Validator::make(array('email' => $name), array('email' => 'email'));
        if (!$validator->fails()) {
            return 1;
        }
        //短信获取验证码
        //验证手机号码
        if (preg_match("/^1[3456789][0-9]{9}$/", $name)) {
            return 2;
        }
        return 0;
    }

    /*     *
     * @description : 版本号比较 
     * @param: $va 
     * @param: $vb 
     * @return: 0 a=b , 1 a>b, -1 a<b
     */

    public function compareVison($va, $vb) {
        $arr_av = explode('.', $va);
        $arr_vb = explode('.', $vb);
        foreach ($arr_av as $key => $value) {
            if (intval($value) > intval($arr_vb[$key])) {
                return 1;
            } else if (intval($value) < intval($arr_vb[$key])) {
                return -1;
            }
        }
        return 0;
    }

    /*     *
     * @description : 异或加密  
     * @param: $str，$key  
     * @return:  $str
     */

    public function xor_enc($str, $key = 'WelcomeToBeiJing') {
        $crytxt = '';
        $keylen = strlen($key);
        for ($i = 0; $i < strlen($str); $i++) {
            $k = $i % $keylen;
            $crytxt .= $str[$i] ^ $key[$k];
        }
        return $crytxt;
    }

    /*     *
     * @description : 增则替换html内容
     * @param: $str 替换前
     * @return:  $str 替换后
     */

    public function pregReplaceContent($str = '') {
        $str = preg_replace('/font-size\s*:.*?((px|em|rem|%)|(?=(;|"|\')))/i', '', $str);
        $str = preg_replace('/line-height\s*:.*?((px|em|rem|%)|(?=(;|"|\')))/i', '', $str);
        $str = str_replace('_ueditor_page_break_tag_', '', $str);
        $str = preg_replace('/(\<video[^>]*width.*?=.*?)[\"\'].*?[\"\']/', '\1"100%"', $str);
        $str = preg_replace('/(\<video[^>]*height.*?=.*?)[\"\'].*?[\"\']/', '\1"auto"', $str);
        $str = preg_replace('/(<video.*?)/', '$1 style="max-height:5rem"', $str);
        $str = preg_replace('/(\<iframe[^>]*width.*?=\s*)[\"\'\S].*?[\"\'\s ]/', '\1"100%" ', $str);
        $str = preg_replace('/(\<embed[^>]*width.*?=\s*)[\"\'\S].*?[\"\'\s ]/', '\1"100%" ', $str);
//        $str = preg_replace('/(\<iframe[^>]*height.*?=.*?)[\"\'].*?[\"\']/', '\1"auto"', $str);
        $str = preg_replace('/(<iframe.*?)/', '$1 style="max-height:5rem"', $str);
//        $str = preg_replace('/(\<img[^>]*width.*?=.*?)[\"\'].*?[\"\']/', '\1"100%"', $str);
        $str = preg_replace('/(<img.*?)/', '$1 style="max-width:100%"', $str);
//        $str = preg_replace('/(<table.*?)/','$1 style="max-width:100%"',$str);
        $str = preg_replace('/(\<table[^>]*width.*?:\s*)\d+/', '\1 100%', $str);
        $str = preg_replace('/(\<table[^>]*100%.*?)px/', '\1 ', $str);
        $str = preg_replace('/(\<table[^>]*100%.*?)rem/', '\1 ', $str);
        $str = preg_replace('/(\<img[^>]*height.*?=.*?)[\"\'].*?[\"\']/', '\1"auto"', $str);
        $str = preg_replace('/(\<audio[^>]*width.*?=.*?)[\"\'].*?[\"\']/', '\1"100%"', $str);
        $str = preg_replace('/(\<audio[^>]*height.*?=.*?)[\"\'].*?[\"\']/', '\1"auto"', $str);
        return $str;
    }

    /*     *
     * @description : 截取字符串之间的值
     * @param:  
     * @return:  
     */

    public function getNeedBetween($kw, $mark1, $mark2 = null) {
        $st = strrpos($kw, $mark1) + strlen($mark1) - 1;
        $ed = strrpos($kw, $mark2);
        if ($mark2 === null) {
            $ed = strlen($kw);
        }
        if (($st == false || $ed == false) || $st >= $ed) {
            return 0;
        }
        $kw = substr($kw, ($st + 1), ($ed - $st - 1));
        return $kw;
    }

    /*     *
     * @description : 
     * @param: $name， 用户名 email or phone
     * @return: 0 都不是  1 email 2 phone
     */

    public function getUuid($id) {
        if(!$id){
            return '';
        }
        $key = env('USER_PRE') . $this->uuidKey;
        return md5($key . md5($id)) . $id;
    }

    /*     *
     * @description : 校验参数是否是用户名 0 都不是  1 email 2 phone
     * @param: $name， 用户名 email or phone
     * @return: 0 都不是  1 email 2 phone
     */

    public function getId($uuid) {
        //截取后
        $uIdArr = explode(',', $uuid);
        $idArr = [];
        foreach ($uIdArr as $k => $val) {
            $id = '';
            $id = substr($val, 32);
            $key = env('USER_PRE') . $this->uuidKey;
            if (md5($key . md5($id)) === substr($val, 0, 32)) {
                $idArr[] = $id;
            }
        }
        return implode(',', $idArr);
    }

    public function debugQueryLog() {
        if (env('OPEN_QUREYLOG')) {
            $action = trim(strrchr($this->request->route()[1]['uses'], '@'), '@');
            $queries = DB::connection(env('MYSQL_CONNECTION', 'mysql'))->getQueryLog();
            $countTime = 0;
            $sqlCountTimes = 0;
            foreach ($queries as $key => $value) {
                unset($queries[$key]['bindings']);
                $countTime += $queries[$key]['time'];
                $sqlCountTimes ++;
            }
            $debugCache = new BaseCache();
            $debugCache->method = 'get';
            $debugCache->cacheName = 'debug';
            $debugCache->cachePar = array($action); //集合
            $retCache = $debugCache->HandleCache();
            if (isset($retCache['times']) && time() - strtotime($retCache['record_data']) < 3600) {
                $retCache['times'] += 1;
                $retCache['sum_time'] += microtime(TRUE) - $_SERVER['REQUEST_TIME_FLOAT'];
                if ($countTime) {
                    $retCache['has_sql_times'] += 1;
                    $retCache['sql_times'] += $sqlCountTimes;
                    $retCache['sum_sql_time'] += $countTime / 1000;
                }
            } else {
                $retCache = array();
                $retCache['record_data'] = date('Y-m-d H:i:s');
                $retCache['times'] = 1;
                $retCache['sum_time'] = microtime(TRUE) - $_SERVER['REQUEST_TIME_FLOAT'];
                if ($sqlCountTimes) {
                    $retCache['has_sql_times'] = 1;
                    $retCache['sql_times'] = $sqlCountTimes;
                    $retCache['sum_sql_time'] = $countTime / 1000;
                } else {
                    $retCache['has_sql_times'] = 0;
                    $retCache['sql_times'] = 0;
                    $retCache['sum_sql_time'] = 0;
                }
            }
            $debugCache->method = 'put';
            $debugCache->cacheValue = $retCache;
            $debugCache->HandleCache();
        }
    }

    //获取随机的大写字符
    public function getRandChar($length) {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    public function getRandImg() {
        $i = 0;
        while (1) {
            $i++;
            $icon = env('HEAD_ICON_' . $i, 'END');
            if ($icon == 'END') {
                break;
            }
        }

        $img = 'd696dba59141c18817a47d587a9a9103';
        if ($i) {
            $img = env('HEAD_ICON_' . rand(1, $i), 'd696dba59141c18817a47d587a9a9103');
        }
        return $img;
    }

    public function readStreamFile() {
//        $url = 'http://1.202.169.180/channels/tvie/hnhp/m3u8:sd';
//        $url = 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8';
//        $fp=fopen($url,'r');
//        while (!feof($fp)){
//            $str = fread($fp,1024);//每次读出文件10分之1
//            echo $str;
//        }
//        $ret = file_get_contents($url);
//        file_put_contents('test', $ret);
        $url = 'http://img.paas.onairm.cn/f8efedb7aeb5bc1fe66c89ebee4e6799base'; 
        $fp=fopen($url,'r');
        $i= 20;
        $str = '';
        while (!feof($fp)){
            $str .= fread($fp,1024);//每次读出文件10分之1
            $i--;
            if(!$i){
                break;
            }
        }
        file_put_contents('test', $str);
        exit();
    }

}
